﻿namespace RS.CmeFastHandler
{
	using OpenFAST;
	using OpenFAST.Template.Loader;
	using System;
	using System.Data;
	using System.IO;
	using Tigera.LibCommon;

	public class Common
	{


		public static bool templateLoadFinished = false;

		static string tCONFIGFILE = "";
		static XMLMessageTemplateLoader templateLoader;	// new XMLMessageTemplateLoader { LoadTemplateIdFromAuxId = true };
		static StreamReader templateSource;
		static string tTEMPLATEFILE = "";



		#region Properties

		public static string CONFIGFILE
		{
			get
			{
				return tCONFIGFILE;
			}
			set
			{
				Common.tCONFIGFILE = value;
			}
		}

		public static string TEMPLATEFILE
		{
			get
			{
				return tTEMPLATEFILE;
			}
			set
			{
				Common.tTEMPLATEFILE = value;
			}
		}

		#endregion Properties



		public static OpenFAST.Message Decode2Msg(byte[] buffer)
		{
			//
			try
			{
				MemoryStream ms = new MemoryStream(buffer, 5, buffer.Length - 5);
				StreamReader is1 = new StreamReader(ms);//2010-8-9 modify
				MessageInputStream mis = new MessageInputStream(is1.BaseStream);
				mis.SetTemplateRegistry(templateLoader.TemplateRegistry);
				OpenFAST.Message md = mis.ReadMessage();
				ms.Close();
				is1.Dispose();
				mis.Context.Reset();
				mis.Close();//2010-8-2 modify
				return md;
			}
			catch (Exception ex)
			{	//记录未知类型数据
				TiTracer.TraceDebug(string.Format("{0},\r\n{1}", ex.Message.ToString(), ex.StackTrace));
				return null;
			}
		}

		public static string Decode2String(byte[] buffer)
		{
			StreamReader is1 = new StreamReader(new MemoryStream(buffer));
			MessageInputStream mis = new MessageInputStream(is1.BaseStream);
			mis.SetTemplateRegistry(templateLoader.TemplateRegistry);
			OpenFAST.Message md = mis.ReadMessage();
			return md.ToString();
		}

		/// <summary>
		/// 从Config.xml文件上获取所有IP列表
		/// </summary>
		/// <param name="ds"></param>
		/// <returns></returns>
		public static DataTable GetAddressTable()
		{
			DataSet ds = new DataSet();
			ds.ReadXml(CONFIGFILE);

			DataTable tbAddress = new DataTable();
			// Init columns for address table
			//connections_Id,channel_id,channel_label ,protocol ,ip ,host-ip ,port ,feed ,connection_id,feed-type ,type_Text
			tbAddress.Columns.Add("connections_Id");
			tbAddress.Columns.Add("channel_id");
			tbAddress.Columns.Add("channel_label");
			tbAddress.Columns.Add("protocol");
			tbAddress.Columns.Add("ip");
			tbAddress.Columns.Add("host-ip");
			tbAddress.Columns.Add("port");
			tbAddress.Columns.Add("feed");
			tbAddress.Columns.Add("id");
			tbAddress.Columns.Add("connection_id");
			tbAddress.Columns.Add("feed-type");
			tbAddress.Columns.Add("type_Text");
			// Hidden columns
			tbAddress.Columns["connections_Id"].ColumnMapping = MappingType.Hidden;
			tbAddress.Columns["connection_id"].ColumnMapping = MappingType.Hidden;

			//Step 1 Set values(connections_Id,protocol ,ip ,host-ip ,port ,feed,id ,connection_id) from table connection
			for (int i = 0; i < ds.Tables["connection"].Rows.Count; i++)
			{
				DataRow row = tbAddress.NewRow();
				row["connections_Id"] = ds.Tables["connection"].Rows[i]["connections_Id"].ToString();
				row["protocol"] = ds.Tables["connection"].Rows[i]["protocol"].ToString();
				row["ip"] = ds.Tables["connection"].Rows[i]["ip"].ToString();
				row["host-ip"] = ds.Tables["connection"].Rows[i]["host-ip"].ToString();
				row["port"] = ds.Tables["connection"].Rows[i]["port"].ToString();
				row["feed"] = ds.Tables["connection"].Rows[i]["feed"].ToString();
				row["id"] = ds.Tables["connection"].Rows[i]["id"].ToString();
				row["connection_id"] = ds.Tables["connection"].Rows[i]["connection_id"].ToString();
				tbAddress.Rows.Add(row);
			}
			//Step 2 Set values(channel_id,channel_label) from table channel
			for (int i = 0; i < tbAddress.Rows.Count; i++)
			{
				for (int j = 0; j < ds.Tables["channel"].Rows.Count; j++)
				{
					if (tbAddress.Rows[i]["connections_Id"].ToString() == ds.Tables["channel"].Rows[j]["channel_Id"].ToString())
					{
						tbAddress.Rows[i]["channel_id"] = ds.Tables["channel"].Rows[j]["id"].ToString();
						tbAddress.Rows[i]["channel_label"] = ds.Tables["channel"].Rows[j]["label"].ToString();
						break;
					}
				}
			}
			//Step 3 Set values(feed-type ,type_Text) from table type
			for (int i = 0; i < tbAddress.Rows.Count; i++)
			{
				for (int j = 0; j < ds.Tables["type"].Rows.Count; j++)
				{
					if (tbAddress.Rows[i]["connection_Id"].ToString() == ds.Tables["type"].Rows[j]["connection_Id"].ToString())
					{
						tbAddress.Rows[i]["feed-type"] = ds.Tables["type"].Rows[j]["feed-type"].ToString();
						tbAddress.Rows[i]["type_Text"] = ds.Tables["type"].Rows[j]["type_Text"].ToString();
						break;
					}
				}
			}
			return tbAddress;
		}

		/// <summary>
		/// Get UDP and Tcp address
		/// </summary>
		/// <param name="channelid"></param>
		/// <param name="udptype"></param>
		/// <returns></returns>
		public static ConnectionInfo GetAllAddress(string channelid, CHANNELTYPE udptype)
		{
			ConnectionInfo address = new ConnectionInfo();
			DataTable tb = GetAddressTable();
			DataRow[] rows = tb.Select("channel_id='" + channelid + "' and [feed-type]='" + udptype.ToString() + "'");
			for (int i = 0; i < rows.Length; i++)
			{
				// A
				if (rows[i]["feed"].ToString() == "A")
				{
					address.UdpA = rows[i]["ip"].ToString();
					address.UdpA_Port = int.Parse(rows[i]["port"].ToString());
				}
				// B
				if (rows[i]["feed"].ToString() == "B")
				{
					address.UdpB = rows[i]["ip"].ToString();
					address.UdpB_Port = int.Parse(rows[i]["port"].ToString());
				}
				//Tcp
				if (rows[i]["feed-type"].ToString() == "H")
				{
					address.Tcp = rows[i]["host-ip"].ToString();
					address.Tcp_Port = int.Parse(rows[i]["port"].ToString());
				}
			}
			return address;
		}

		/// <summary>
		/// Get TCP address
		/// </summary>
		/// <param name="channelid"></param>
		/// <returns></returns>
		public static ConnectionInfo GetTcpAddress(string channelid)
		{
			ConnectionInfo address = new ConnectionInfo();
			DataTable tb = GetAddressTable();
			DataRow[] rows = tb.Select("channel_id='" + channelid + "' and [feed-type]='" + CHANNELTYPE.H.ToString() + "'");
			for (int i = 0; i < rows.Length; i++)
			{
				// A
				//if (rows[i]["feed"].ToString() == "A")
				{
					address.Tcp = rows[i]["host-ip"].ToString();
					address.Tcp_Port = int.Parse(rows[i]["port"].ToString());
				}
			}
			return address;
		}

		/// <summary>
		/// Get UDP address
		/// </summary>
		/// <param name="channelid"></param>
		/// <param name="udptype"></param>
		/// <returns></returns>
		public static ConnectionInfo GetUdpAddress(string channelid, CHANNELTYPE udptype)
		{
			ConnectionInfo address = new ConnectionInfo();
			DataTable tb = GetAddressTable();
			DataRow[] rows = tb.Select("channel_id='" + channelid + "' and [feed-type]='" + udptype.ToString() + "'");
			for (int i = 0; i < rows.Length; i++)
			{
				// A
				if (rows[i]["feed"].ToString() == "A")
				{
					address.UdpA = rows[i]["ip"].ToString();
					address.UdpA_Port = int.Parse(rows[i]["port"].ToString());
				}
				// B
				if (rows[i]["feed"].ToString() == "B")
				{
					address.UdpB = rows[i]["ip"].ToString();
					address.UdpB_Port = int.Parse(rows[i]["port"].ToString());
				}
			}
			return address;
		}

		public static void InitCommon()
		{
			if (templateLoadFinished == false)
			{
				templateSource = new StreamReader(TEMPLATEFILE);
				templateLoader = new XMLMessageTemplateLoader { LoadTemplateIdFromAuxId = true };
				templateLoader.Load(templateSource.BaseStream);
				templateLoadFinished = true;
			}
		}


	}
}